package com.rainwen.shiro.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

import static com.rainwen.shiro.constant.ContextConstants.SESSION_URL_PERMISSION;

/**
 * Url权限拦截
 *
 * @author rain.wen
 * @date 2018/1/15.
 */
public class UrlPermissionFilter extends PermissionsAuthorizationFilter {

    private final static Logger logger = LoggerFactory.getLogger(UrlPermissionFilter.class);

    @Override
    public boolean isAccessAllowed(ServletRequest request,
                                   ServletResponse response, Object mappedValue) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        HttpSession session = req.getSession();
        Object urlPermissionObj = session.getAttribute(SESSION_URL_PERMISSION);
        if(urlPermissionObj == null) {
            return false;
        }
        Map<String, String> urlPermissionMap = (Map<String, String>) urlPermissionObj;
        if(StringUtils.isBlank(uri)) {
            return true;
        }
        if(urlPermissionMap.containsKey(uri)) {
            return true;
        }

        String baseUri = StringUtils.substringBeforeLast(uri, "/");
        if(urlPermissionMap.containsKey(baseUri)) {
            return true;
        }

        logger.info("{} unauthorized ", uri);
        return false;

    }
}
